import requests
import re
import execjs
from lxml import etree

requests = requests.session()
headers = {
    'Host': 'www.fangdi.com.cn',
    'Referer': 'http://www.fangdi.com.cn/service/service_law_detail_img2.html',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
}
url = 'http://www.fangdi.com.cn/index.html'


def first_request():
    response = requests.get(url, headers=headers)
    obj_html = etree.HTML(response.text)
    content_data = obj_html.xpath('//meta[2]/@content')[0]
    func_code = obj_html.xpath('//script[2]/text()')[0]
    return content_data, func_code


def second_request():
    content_data, func_code = first_request()
    # print(content_data, func_code)
    with open('main.js', encoding='utf-8') as f:
        js_code = f.read().replace('content_data', content_data).replace("'func_code'", func_code)
    # print(js_code)
    js = execjs.compile(js_code)
    cookies = {'FSSBBIl1UgzbN7N80T': js.call('get_cookie').split(';')[0].split('=')[-1]}
    print(cookies)
    res = requests.get(url, headers=headers, cookies=cookies)
    res.encoding = res.apparent_encoding
    print(res.request.headers)
    print(res)
    print(res.text)
    # second_request()


second_request()